package com.example.demo.annotationdemo;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * @Description 注解解析
 * @Author sonxulin
 * @Date 2020/1/3 19:58
 **/
public class ParseAnn {
    public static void main(String[] args) {

        try {
            //1.使用类加载器加载类
            Class<?> c = Class.forName("com.example.demo.annotationdemo.Child");
            //2.找到类上的注解
            boolean isExist = c.isAnnotationPresent(Description.class);
            if(isExist){
                //3.拿到注解实例
                Description annotation = c.getAnnotation(Description.class);
                System.out.println(annotation.desc());
            }

            //4.拿到方法上的注解
            Method[] methods = c.getMethods();
            for (Method method : methods) {
                boolean annotationPresent = method.isAnnotationPresent(Description.class);
                if(annotationPresent){
                    Description annotation = method.getAnnotation(Description.class);
                    System.out.println(annotation.desc());
                }
            }

            //另外一种解析方法
            for (Method method : methods) {
                Annotation[] annotations = method.getAnnotations();
                for (Annotation annotation : annotations) {
                    if(annotation instanceof Description){
                        System.out.println(((Description) annotation).desc());
                    }
                }
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
